package com.jeesite.modules.fl.web.app;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.ServiceException;
import com.jeesite.common.utils.SmsUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.fl.entity.Content;
import com.jeesite.modules.fl.entity.Leaguer;
import com.jeesite.modules.fl.service.AppointmentService;
import com.jeesite.modules.fl.service.ContentService;
import com.jeesite.modules.sys.entity.DictType;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.DictTypeService;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.sys.utils.ValidCodeUtils;
import net.sf.jmimemagic.MagicParseException;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RequestMapping({"/app"})
@Controller
public class AppController extends BaseController {
    @Autowired
    private DictTypeService dictTypeService;
    @Autowired
    private UserService userService;
    @Autowired
    private ContentService contentService;
    @Autowired
    private AppointmentService appointmentService;
    private static final Logger logger = LoggerFactory.getLogger(AppController.class);


    @RequestMapping("/session")
    @ResponseBody
    public String getSessionId(){
        Session session = UserUtils.getSession();
        return (String)session.getId();
    }

    /**
     * 得到注册验证码
     * @param user
     * @param validType
     * @param request
     * @return
     */
    @PostMapping({"getRegValidCode"})
    @ResponseBody
    public String getRegValidCode(User user, String validType, HttpServletRequest request) {
       /* if (!ValidCodeUtils.validate(request, validCode)) {
            return this.renderResult("false", "图片验证码不正确或已失效，请点击图片刷新！");
        } else */
       if (!"mobile".equals(validType)) {
            return this.renderResult("false", "非法操作。");
        } else if (StringUtils.isNotBlank(user.getLoginCode())) {
            if ("mobile".equals(validType) && !StringUtils.isNotBlank(user.getLoginCode())) {
                return this.renderResult("false", "手机号码不能为空！");
            } else {
                Date date = (Date) UserUtils.getCache("regLastDate");
                if (date != null && (System.currentTimeMillis() - date.getTime()) / 1000L < 20L) {
                    return this.renderResult("false", "您当前操作太频繁，请稍等一会再操作！");
                } else {
                    UserUtils.putCache("regLastDate", new Date());
                    if (UserUtils.getByLoginCode(user.getLoginCode()) != null) {
                        return this.renderResult("false", "登录账号已存在！");
                    } else {
                        String code = StringUtils.getRandomNum(6);
                        UserUtils.putCache("regCorpCode", user.getCorpCode());
                        UserUtils.putCache("regCorpName", user.getCorpName());
                        UserUtils.putCache("regLoginCode", user.getLoginCode());
                        UserUtils.putCache("regUserType", user.getUserType());
                        UserUtils.putCache("regMobile", user.getLoginCode());
                        UserUtils.putCache("regValidCode", code);
                        logger.debug(user.getLoginCode()+" 的注册码为：" + code);
                        return "mobile".equals(validType) ? SmsUtils.send(user.getLoginCode(), SmsUtils.getTemplate("register"), new String[]{code}) : renderResult(Global.TRUE, "非法操作");
                        /*String[] userTypes = StringUtils.split(Global.getConfig("sys.account.registerUser.userTypes.userTypes", "-1"), ",");
                        if (StringUtils.inString(user.getUserType(), userTypes)) {
                            UserUtils.putCache("regUserType", user.getUserType());
                            UserUtils.putCache("regMobile", user.getLoginCode());
                            UserUtils.putCache("regValidCode", code);
                            if ("send_email".equals(validType)) {
                                return this.sendEmailValidCode(user, code, "注册账号");
                            } else {
                                return "send_mobile".equals(validType) ? this.sendSmsValidCode(user, code, "注册账号") : null;
                            }

                        } else {
                            return this.renderResult("false", "非法的用户类型！");
                        }*/
                    }
                }
            }
        } else {
            return this.renderResult("false", "登录账号和用户姓名不能为空！");
        }
    }

    /**
     * 保存注册
     * @param user
     * @param regValidCode
     * @param request
     * @return
     */
    @PostMapping({"saveRegByValidCode"})
    @ResponseBody
    public String saveRegByValidCode(User user, String regValidCode, HttpServletRequest request) {
        String corpCode = (String) UserUtils.getCache("regCorpCode");
        String corpName = (String) UserUtils.getCache("regCorpName");
        String userType = (String) UserUtils.getCache("regUserType");
        String loginCode = (String) UserUtils.getCache("regLoginCode");
        String mobile = (String) UserUtils.getCache("regMobile");
        String validCode = (String) UserUtils.getCache("regValidCode");
        Date date = (Date) UserUtils.getCache("regLastDate");
        if (loginCode != null && loginCode.equals(user.getLoginCode())) {
            boolean isTimeout = true;
            String validTime = Global.getConfig("sys.account.validCodeTimeout", "10");
            if ("0".equals(validTime) || date != null && (System.currentTimeMillis() - date.getTime()) / 1000L < 60L * Long.parseLong(validTime)) {
                isTimeout = false;
            }

            if (validCode != null && validCode.equals(regValidCode) && !isTimeout) {
                if (StringUtils.isNotBlank(user.getLoginCode()) && StringUtils.isNotBlank(user.getUserName())) {
                    User u = new User();
                    u.setIsNewRecord(true);
                    if (StringUtils.isNotBlank(corpCode)) {
                        u.setCorpCode(corpCode);
                        u.setCorpName(corpName);
                    }

                    u.setLoginCode(loginCode);
                    u.setUserName(user.getUserName());
                    u.setPassword(user.getPassword());
                    u.setMobile(mobile);
                    u.setUserType(userType);
                    u.setMgrType("0");
                    //this.userService.save(u);
                    UserUtils.removeCache("regUserType");
                    UserUtils.removeCache("regLoginCode");
                    UserUtils.removeCache("regValidCode");
                    UserUtils.removeCache("regLastDate");
                    return this.renderResult("true", "恭喜你，您的账号 " + u.getLoginCode() + " 注册成功！");
                } else {
                    return this.renderResult("false", "登录账号和用户姓名不能为空！");
                }
            } else {
                return this.renderResult("false", "验证码不正确或已失效，请重新获取验证码！");
            }
        } else {
            return this.renderResult("false", "非法操作。");
        }
    }

    @RequestMapping({"listDictType"})
    @ResponseBody
    public Page<DictType> listDictType(DictType dictType, HttpServletRequest request, HttpServletResponse response) {
        return this.dictTypeService.findPage(new Page(request, response), dictType);
    }

    /**
     * 得到忘记密码验证码
     * @param user
     * @param validType
     * @param request
     * @return
     */
    @PostMapping({"getFpValidCode"})
    @ResponseBody
    public String getFpValidCode(User user, String validType, HttpServletRequest request) {
       /* if (!ValidCodeUtils.validate(request, validCode)) {
            return this.renderResult("false", "图片验证码不正确或已失效，请点击图片刷新！");
        } else */
       if (!"mobile".equals(validType)) {
            return this.renderResult("false", "非法操作。");
        } else {
            User u = UserUtils.getByLoginCode(user.getLoginCode());
            if (u == null) {
                return renderResult("false", "登录账号不正确！");
            }
           Date date = (Date)UserUtils.getCache("fpLastDate");
           if (date != null && (System.currentTimeMillis() - date.getTime()) / 1000L < 20L) {
               return renderResult("false", "您当前操作太频繁，请稍等一会再操作！");
           } else {
               UserUtils.putCache("fpLastDate", new Date());
               String fpValidCode = StringUtils.getRandomNum(6);
               UserUtils.putCache("fpLoginCode", u.getLoginCode());
               UserUtils.putCache("fpValidCode", fpValidCode);
               return SmsUtils.send(user.getLoginCode(), SmsUtils.getTemplate("forgotPwd"), new String[]{fpValidCode});
               //return renderResult("true", "验证码："+ fpValidCode);
           }
        }
    }

    /**
     * 保存密码
     * @param user
     * @param fpValidCode
     * @param request
     * @return
     */
    @PostMapping({"savePwdByValidCode"})
    @ResponseBody
    public String savePwdByValidCode(User user, String fpValidCode, HttpServletRequest request) {
        String loginCode = (String)UserUtils.getCache("fpLoginCode");
        String validCode = (String)UserUtils.getCache("fpValidCode");
        Date date = (Date)UserUtils.getCache("fpLastDate");
        if (loginCode != null && loginCode.equals(user.getLoginCode())) {
            UserUtils.removeCache("fpLoginCode");
            UserUtils.removeCache("fpValidCode");
            UserUtils.removeCache("fpLastDate");
            boolean isTimeout = true;
            String validTime = Global.getConfig("sys.account.validCodeTimeout", "10");
            if ("0".equals(validTime) || date != null && (System.currentTimeMillis() - date.getTime()) / 1000L < 60L * Long.parseLong(validTime)) {
                isTimeout = false;
            }

            if (validCode != null && validCode.equals(fpValidCode) && !isTimeout) {
                try {
                    userService.updatePassword(loginCode, user.getPassword());
                } catch (ServiceException var11) {
                    return this.renderResult("false", var11.getMessage());
                }

                return this.renderResult("true", "恭喜你，您的账号 " + loginCode + " 密码修改成功！");
            } else {
                return this.renderResult("false", "验证码不正确或已失效，请重新获取验证码！");
            }
        } else {
            return this.renderResult("false", "请重新获取验证码！");
        }
    }

    @GetMapping({"ownerReport"})
    @ResponseBody
    @RequiresUser
    public Map<String,Object> getOwnerReport(String lang){
        Map<String,Object> map = new HashMap<String,Object>();
        if(StringUtils.isBlank(lang)) lang="1";
        int notViewType3Count = contentService.getNotViewType3Count(lang);
        int unReadEvalCount = appointmentService.getUnReadEvalCount(UserUtils.getUser().getRefCode());
        map.put("NotViewType3Count", notViewType3Count);
        map.put("UnReadEvalCount", unReadEvalCount);
        return map;
    }
}
